﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pku.BookStore.Web.Controllers
{
    [UserAuthorizeAttribute]
    public class UserController : Controller
    {
        //
        // GET: /User/

        #region 首页
        public ActionResult Index()
        {
            IServices.IOrderFormServices orderformDal = new Services.OrderFormServices();
            //取最新5个订单
            Model.OrderFormParam orderParam = new Model.OrderFormParam();
            orderParam.PageNo = 1;
            orderParam.PageRow = 5;
            orderParam.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            orderParam.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            orderParam.UserName = Session["UserName"].ToString();
            var orderList = orderformDal.Search(orderParam);
            return View(orderList);
        }
        #endregion

        #region 登录、注册
        public ActionResult LogOn(string Act)
        {
            if (Act == "LogOut")
            {
                Session["UserID"] = null;
                Session["UserName"] = null;
                Session["LastLoginTime"] = null;
                Session["LastIP"] = null;
                Session["LevelID"] = null;
                return RedirectToAction("LogOn", "User");
            }
            if (Session["EmployeeID"] != null)
            {
                return RedirectToAction("Index", "User");
            }
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(Model.UserModel model)
        {
            model.UserPwd = Utility.EncryptHelper.MD5(model.UserPwd);
            IServices.IUserServices userDal = new Services.UserServices();
            var logonResult = userDal.Login(model);
            if (logonResult != null)
            {
                Session["UserID"] = logonResult.UserID;
                Session["UserName"] = logonResult.UserName;
                Session["LastLoginTime"] = logonResult.LastLoginTime;
                Session["LastIP"] = logonResult.LastIP;
                Session["LevelID"] = logonResult.LevelID;
                return RedirectToAction("Index", "User");
            }
            else
            {
                ModelState.AddModelError("LoginError", "用户名或密码错误");
            }
            return View();
        }

        public ActionResult Reg()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Reg(Model.UserModel model)
        {
            if (string.IsNullOrEmpty(model.UserName))
            {
                ModelState.AddModelError("Info", "用户名不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.UserPwd))
            {
                ModelState.AddModelError("Info", "密码不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Email))
            {
                ModelState.AddModelError("Info", "邮箱不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.TrueName))
            {
                ModelState.AddModelError("Info", "真实姓名不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Phone))
            {
                ModelState.AddModelError("Info", "电话不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Mobile))
            {
                ModelState.AddModelError("Info", "手机号不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Province))
            {
                ModelState.AddModelError("Info", "省份不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.City))
            {
                ModelState.AddModelError("Info", "市不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Area))
            {
                ModelState.AddModelError("Info", "区不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.Address))
            {
                ModelState.AddModelError("Info", "地址不能为空");
                return View();
            }
            if (string.IsNullOrEmpty(model.PostCode))
            {
                ModelState.AddModelError("Info", "邮编不能为空");
                return View();
            }

            IServices.IUserServices userDal = new Services.UserServices();
            model.UserPwd = Utility.EncryptHelper.MD5(model.UserPwd);
            model.IsLock = 1;
            model.LastIP = Request.UserHostAddress == "::1" ? "127.0.0.1" : Request.UserHostAddress;
            if (userDal.Exist(model.UserName, 0))
            {
                ModelState.AddModelError("Info", "用户名已存在，请更换");
                return View();
            }
            if (userDal.Exist(model.Email, 1))
            {
                ModelState.AddModelError("Info", "邮箱已存在，请更换");
                return View();
            }
            if (userDal.Add(model) != 0)
            {
                return Redirect("/User/LogOn");
            }
            else
            {
                ModelState.AddModelError("Info", "操作不成功，请联系管理员");
            }

            return View();
        }
        #endregion

        #region 用户
        public ActionResult UserInfo(string Act, Model.UserModel model)
        {
            int UserID = Convert.ToInt32(Session["UserID"]);
            IServices.IUserServices userDal = new Services.UserServices();

            if (Act == "E")
            {
                model.UserID = Convert.ToInt32(Session["UserID"]);
                if (userDal.Modify(model))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }

            var userModel = userDal.GetEntityById(UserID);
            if (userModel == null) userModel = new Model.UserModel();
            return View(userModel);
        }

        public ActionResult UserPass(string Act, Model.UserModel model, string UserPassNew, string UserPassNew2)
        {
            int UserID = Convert.ToInt32(Session["UserID"]);
            IServices.IUserServices userDal = new Services.UserServices();
            if (Act == "E")
            {
                if (UserPassNew != UserPassNew2)
                {
                    ModelState.AddModelError("Info", "两次输入密码不一致，请核查");
                }
                else
                {
                    model.UserPwd = Utility.EncryptHelper.MD5(model.UserPwd);
                    model.UserName = Session["UserName"].ToString();
                    if (userDal.Login(model) == null)
                    {
                        ModelState.AddModelError("Info", "密码不正确，请核查");
                    }
                    else
                    {
                        model.UserPwd = Utility.EncryptHelper.MD5(UserPassNew);
                        model.UserID = UserID;
                        if (userDal.ModifyPass(model))
                        {
                            ModelState.AddModelError("Info", "操作成功");
                        }
                        else
                        {
                            ModelState.AddModelError("Info", "操作失败请联系管理员");
                        }
                    }
                }
            }


            var userModel = userDal.GetEntityById(UserID);
            return View(userModel);
        }
        #endregion

        #region 订单
        public ActionResult OrderList(int? p)
        {
            if (p == null) p = 1;
            IServices.IOrderFormServices orderDal = new Services.OrderFormServices();
            ViewBag.OrderCount = orderDal.GetCount(null);

            var param = new Model.OrderFormParam();
            param.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            param.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            param.UserName = Session["UserName"].ToString();
            var orderList = orderDal.Search(param);


            return View(orderList);
        }

        public ActionResult OrderEdit(int? ID, string Act, Model.OrderFormModel model)
        {
            if (ID == null) ID = 0;
            IServices.IOrderFormServices orderDal = new Services.OrderFormServices();

            if (Act == "E")
            {
                model.OrderID = Convert.ToInt32(ID);
                model.OrderStatus = -1;
                if (orderDal.ModifyStatus(model, Convert.ToInt32(Session["UserID"])))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }

            var statusListr = Utility.EnumHelper.GetCachedDictionary(typeof(Utility.EnumUtility.OrderStatus));
            List<SelectListItem> Items = new List<SelectListItem>();
            foreach (var item in statusListr)
            {
                Items.Add(new SelectListItem { Value = item.Key, Text = item.Value });
            }
            ViewBag.statusList = Items;
            var orderModel = orderDal.GetEntityById(Convert.ToInt32(ID));
            return View(orderModel);
        }
        #endregion

        #region 收藏
        public ActionResult FavoritesList()
        {
            IServices.IFavoritesServices favoritesDal = new Services.FavoritesServices();

            Model.FavoritesParam param = new Model.FavoritesParam();
            param.UserID = Convert.ToInt32(Session["UserID"]);
            var favoritesList = favoritesDal.Search(param);

            return View(favoritesList);
        }

        public ActionResult FavoritesAct(int? ID, string Act)
        {
            if (ID == null) ID = 0;
            IServices.IFavoritesServices favoritesDal = new Services.FavoritesServices();

            if (Act == "D")
            {
                favoritesDal.Delete(Convert.ToInt32(ID));
            }
            else if (Act == "A")
            {
                if (!favoritesDal.Exist(Convert.ToInt32(ID), Convert.ToInt32(Session["UserID"])))
                {
                    Model.FavoritesModel model = new Model.FavoritesModel();
                    model.BookID = Convert.ToInt32(ID);
                    model.UserID = Convert.ToInt32(Session["UserID"]);
                    favoritesDal.Add(model);
                }
            }

            return Redirect("/User/FavoritesList");
        }
        #endregion
    }
}
